package io.jpom.plugin.netty;

import cn.hutool.extra.ssh.JschUtil;
import cn.jiangzeyin.common.JsonMessage;
import com.alibaba.fastjson.JSONObject;
import com.jcraft.jsch.ChannelSftp;
import com.jcraft.jsch.Session;
import io.netty.channel.Channel;
import io.netty.channel.ChannelProgressiveFuture;
import io.netty.channel.ChannelProgressiveFutureListener;
import io.netty.handler.codec.http.websocketx.TextWebSocketFrame;

/**
 * 下载进度回调
 *
 * @author bwcx_jzy
 * @date 2019/8/14
 */
public class Progress implements ChannelProgressiveFutureListener {
    private Channel channel;
    private String reqId;

    private Session session;
    private ChannelSftp channelSftp;

    private long totalSize;

    public Progress(Channel channel, String reqId, Session session, ChannelSftp channelSftp, long totalSize) {
        this.channel = channel;
        this.reqId = reqId;
        this.session = session;
        this.channelSftp = channelSftp;
        this.totalSize = totalSize;
    }

    @Override
    public void operationProgressed(ChannelProgressiveFuture future, long progress, long total) throws Exception {
        String progressStr = String.format("%.2f", (progress / (double) totalSize) * 100);
        send(progressStr);
    }

    @Override
    public void operationComplete(ChannelProgressiveFuture future) throws Exception {
        //
        send("100");
        JschUtil.close(channelSftp);
        JschUtil.close(session);
    }

    private void send(String data) {
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("event", "progress");
        jsonObject.put("data", data);
        jsonObject.put("reqId", this.reqId);
        channel.writeAndFlush(new TextWebSocketFrame(JsonMessage.getString(200, "", jsonObject)));
    }
}
